12. String Methods

String Methods

ND079 C1 L4 A12 String Method

Java provides advanced memory management for String objects by using a String pool. A String pool is a way of storing only one copy of a String.

To understand this, we have to look at what is happening in memory when we create Strings and assign them to variables. Strings in Java are immutable, meaning they cannot be changed after they are created. When we "change" the String in a variable, what actually happens is that, behind the scenes, Java creates a new String in the String pool—and changes the variable's reference value to point to this new String. The old String object may remain in place, unchanged.

Also note that multiple variables may use the same String reference. This means that if we have two variables with exactly the same String (e.g., "Hello") they will all reference the same String object.

String Pool Demonstration

The best way to understand string pools is to play with them in the code. In this next video, we will demonstrate the concept in IntelliJ.

ND079 C1 L4 A13 Memory Demo

Select the correct statements related to String management in Java.

(Select all that apply.)

SOLUTION:
  • Multiple variables can point to the same String object.
  • String are immutable.

Suppose we declare a new String variable:

String message = "foo";

And then later, we change the value of the string in this variable, like so:

message = "bar";

When we assign this new string, "bar", to the message variable, what happens in the computer's memory?

SOLUTION: The original String object is left unchanged (it still contains the string `"foo"`), but a new String object is created that contains the new String, `"bar"`.

String Methods

ND079 C1 L4 A14 Method Demo

Suppose we have the following String variable:

String text = "I think this is correct";

Which of the following pieces of code would tell us whether the string contains the substring "this"?

SOLUTION: `text.contains("this");`

Substring

ND079 C1 L4 A15 Substring Method

Suppose we have this String variable:

String text = "Happy Days are here again";

How could we create the substring "Happy"?

SOLUTION: `text.substring(0, 5);`